package vashion.azeroth.back.core.exception.resolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import vashion.azeroth.contant.GenericErrorEnum;
import vashion.azeroth.core.result.ApiResult;

import com.alibaba.fastjson.JSON;

public class ExceptionResolver extends SimpleMappingExceptionResolver {
	
	private final static Logger log = LoggerFactory.getLogger(ExceptionResolver.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {

		    log.error("系统异常", ex);
		    
		    if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
		    	HandlerMethod mathod = (HandlerMethod) handler;
		        ResponseBody body = mathod.getMethodAnnotation(ResponseBody.class);
		        //判断有没有@ResponseBody的注解没有的话调用父方法
		        if (body == null) {
		            return super.doResolveException(request, response, handler, ex);
		        }
		    }
	        
	        ModelAndView mv = new ModelAndView();
	        //设置ContentType
	        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
	        //避免乱码
	        response.setCharacterEncoding("UTF-8");
	    try {
	        ApiResult<Boolean> result = ApiResult.newErrorResult(
					GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());
	        response.getWriter().print(JSON.toJSONString(result));
		} catch (Exception e) {
			log.error("", e);
		}

		return mv;
	}

}
